package com.example.library.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.library.common.Result;
import com.example.library.entity.Appointment;
import com.example.library.entity.Book;
import com.example.library.entity.Bookshelf;
import com.example.library.entity.Soldout;
import com.example.library.mapper.BookMapper;
import com.example.library.service.IAppointmentService;
import com.example.library.service.IBookService;
import com.example.library.service.IBookshelfService;
import com.example.library.service.ISoldoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 胡绍杆
 * @since 2022-06-16
 */
@ResponseBody
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private IBookService bookService;
    @Resource
    private ISoldoutService soldoutService;
    @Resource
    private IBookshelfService bookshelfService;
    @Resource
    private BookMapper bookMapper;

    //新增和修改
    @ResponseBody
    @GetMapping("/savebook")
    private Result save(@RequestParam String isbn,
                        @RequestParam String bookname,
                        @RequestParam String pub,
                        @RequestParam String pubDate,
                        @RequestParam String author,
                        @RequestParam Double price,
                        @RequestParam Integer classId,
                        @RequestParam String bookPicture,
                        @RequestParam Integer num12) {
        Book book = new Book();
        book.setIsbn(isbn);
        book.setBookname(bookname);
        book.setPub(pub);
        book.setPubDate(pubDate.substring(0,10));
        book.setAuthor(author);
        book.setPrice(price);
        book.setClassId(classId);
        book.setBookPicture(bookPicture);
        if(book.getBookId() == 0){
            for(int i = 0; i<num12;i++){
                System.out.println(book.toString());
                bookService.save(book);
//            String a = book.getPubDate();
//            book.setPubDate(a.substring(0,10));
            }
        } else {
            bookService.saveOrUpdate(book);
        }
        return Result.success();
    }

    //查询所有数据
    @GetMapping
    public Result index(){
        return Result.success(bookService.list());
    }

    //按条件查询
    @GetMapping("/searchBook")
    public Result searchBook(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam(defaultValue = "") String bookNum,
                             @RequestParam(defaultValue = "") String bookname,
                             @RequestParam(defaultValue = "") String author) {

        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
       if(!bookNum.equals("")){
           queryWrapper.like("book_num", bookNum);
       }
       if(!bookname.equals("")){
           queryWrapper.like("bookname",bookname);
       }
       if(!author.equals("")){
           queryWrapper.like("author",author);
       }
        queryWrapper.orderByDesc("book_id");
        queryWrapper.groupBy("isbn");
        return  Result.success(bookMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper));
    }

    //统计图书数量
    @GetMapping("/bookCount")
    public Result bookCount(@RequestParam String isbn) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isbn",isbn);
        int bookcount=bookService.count(queryWrapper);
        return  Result.success(bookcount);
    }

    //相同图书
    @GetMapping("/sameBook")
    public Result sameBook(@RequestParam String isbn,
                             @RequestParam Integer pageNum,
                             @RequestParam Integer pageSize) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isbn",isbn);
        return  Result.success(bookMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper));
    }

    //上架图书查询
    @GetMapping("/shangjiaAlert")
    public Result shangjiaAlert(@RequestParam String isbn){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isbn",isbn);
        return Result.success(bookService.list(queryWrapper));
    }

    //上架修改数据
    @GetMapping("/shangjia")
    public Result Shangjia(@RequestParam String shelfNum,
                           @RequestParam String bookId) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("book_num", shelfNum);
        queryWrapper.eq("book_state", 1).or().eq("book_state",2);
        int count = bookService.count(queryWrapper);
        if(count==100) {
            return Result.error();
        }
        QueryWrapper<Book> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.like("book_num", shelfNum);
        int count1 = bookService.count(queryWrapper)+1;
        String countStr="";
        if(count1<10){
            countStr="00"+count1;
        }
        else if(count1>=10 && count1<100) {
            countStr="0"+count1;
        }
        String bookNum=shelfNum+"-"+countStr;
        UpdateWrapper updateWrapper=new UpdateWrapper();
        updateWrapper.eq("book_id",bookId);
        updateWrapper.set("book_state",1);
        updateWrapper.set("book_num",bookNum);

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String val1 = formatter.format(date);

        updateWrapper.set("launch_time",val1);
        return Result.success(bookService.update(updateWrapper));
    }

    //图书下架
    @GetMapping("/xiajia")
    public Result UpdateXiajia(@RequestParam(value = "bookNum")String bookNum,
                               @RequestParam(value = "reason")String reason) {
        System.out.println(bookNum);
        System.out.println(reason);
        UpdateWrapper<Book> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("book_num",bookNum);
        updateWrapper.eq("book_state",1);
        updateWrapper.set("book_state",0);
        if(bookService.update(updateWrapper)){
            Soldout soldout=new Soldout();
            soldout.setBookNum(bookNum);
            soldout.setReason(reason);
            soldoutService.save(soldout);
            return Result.success();
        }
        return Result.error();
    }

    //导入
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<Book> list = reader.readAll(Book.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Book> books = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Book book = new Book();
            book.setIsbn(row.get(0).toString());
            book.setBookname(row.get(1).toString());
            book.setPub(row.get(2).toString());
            book.setPubDate(row.get(3).toString());
            book.setAuthor(row.get(4).toString());
            book.setLaunchTime(row.get(5).toString());
            book.setPrice(Double.valueOf(row.get(6).toString()));
            book.setClassId(Integer.valueOf(row.get(7).toString()));
            book.setBookPicture(row.get(8).toString());
            books.add(book);
        }
        bookService.saveBatch(books);
        return Result.success(true);
    }


    //导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Book> list = bookService.list();
        // 通过工具类创建writer 写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/图书信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("bookId", "图书ID");
        writer.addHeaderAlias("isbn", "ISBN");
        writer.addHeaderAlias("bookNum", "索书号");
        writer.addHeaderAlias("bookname", "书名");
        writer.addHeaderAlias("pub", "出版社");
        writer.addHeaderAlias("pubDate", "出版时间");
        writer.addHeaderAlias("author", "作者");
        writer.addHeaderAlias("launchTime", "上架时间");
        writer.addHeaderAlias("price", "价格");
        writer.addHeaderAlias("classId", "分类ID");
        writer.addHeaderAlias("bookState", "状态");
        writer.addHeaderAlias("bookIntroduction", "评分");
        writer.addHeaderAlias("bookPicture", "图片");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("图书信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * yang
     * 用户首页图书列表
     * 根据isbn去重统计图书并返回isbn,bookname
     */
    @GetMapping("/getBookByInfoY")
    public Result getBookByInfoY(@RequestParam Integer pageNum, @RequestParam Integer pageSize,
                                 @RequestParam(defaultValue = "") String inputClassId,
                                 @RequestParam(defaultValue = "") String inputBookName,
                                 @RequestParam(defaultValue = "") String author,
                                 @RequestParam(defaultValue = "") String isbn){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if(!StrUtil.isEmpty(inputBookName)){
            queryWrapper.like("bookname",inputBookName);
        }
        if(!StrUtil.isEmpty(inputClassId)){
            queryWrapper.eq("class_id",inputClassId);
        }
        if(!StrUtil.isEmpty(author)){
            queryWrapper.eq("author",author);
        }
        if(!StrUtil.isEmpty(isbn)){
            queryWrapper.eq("isbn",isbn);
        }
        queryWrapper.select("DISTINCT isbn,bookname,book_picture");
        queryWrapper.orderByDesc("launch_time");
        queryWrapper.in("book_state", 1,2);
        return Result.success(bookService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * yang
     * 用户查看图书详情
     * 根据传入的isbn返回图书详细信息
     */
    @GetMapping("/getBookByIsbnY")
    public Result getBookByIsbnY(@RequestParam(value = "isbn") String isbn){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isbn",isbn).last("LIMIT 1");
        return Result.success(bookService.getOne(queryWrapper));
    }

    /**
     * yang
     * 图书位置
     * 1A-01-001
     */
    @GetMapping("/getBookArea")
    public Result getBookArea(@RequestParam(value = "isbn") String isbn){
        List<Book> books = bookService.list(new QueryWrapper<Book>()
                .select("DISTINCT book_num")
                .eq("isbn",isbn)
                .in("book_state",1,2,4));
        StringBuilder bookNum= new StringBuilder();
        for (int i=0;i<books.size();i++) {
            String str = books.get(i).getBookNum().substring(0,1)+"层"+books.get(i).getBookNum()
                    .substring(1,2)+"区"+books.get(i).getBookNum().substring(3,5)+"号架; ";
            bookNum.append(str);
        }
        return Result.success(bookNum);
    }

    /**
     * yang
     * 图书推荐
     * 若登录，返回自己借阅类型最多的同类书
     */
    @Autowired
    private IAppointmentService iAppointmentService;
    @GetMapping("/getBookByAccountY")
    public Result getBookByAccountY(@RequestParam(value = "account") String account){
        // 查阅自己的借阅前三类别编号，大于三取三

        // 查阅所有借阅记录的类别前三编号，大于三取三

        return Result.success();
    }

    /**
     * yang
     * 新书推荐
     * 返回新上架的部分图书信息
     */
    @GetMapping("/getNewBookY")
    public Result getNewBookY(){
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT isbn,bookname,book_picture").orderByAsc("launch_time")
                .in("book_state", 1,2).last("LIMIT 8");
        return Result.success(bookService.list(queryWrapper));
    }

    /**
     * yang
     * 图书详情
     * 根据book_num返回图书信息
     */
    @GetMapping("/getOneBookY")
    public Result getOneBookY(@RequestParam(value = "bookNum") String bookNum){
        return Result.success(bookService.list(new QueryWrapper<Book>().eq("book_num",bookNum)));
    }
}
